package com.xhji.web.config.redis;

import org.springframework.data.redis.core.RedisOperations;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

public class RedisExpireAtomicLong {
    private String key;
    private RedisOperations<String, Integer> redisOperations;

    public RedisExpireAtomicLong(String key, RedisOperations<String, Integer> redisOperations) {
        this.key = key;
        this.redisOperations = redisOperations;
    }

    public long increment(int delta, Duration duration) {
        return redisOperations.execute(RedisScripts.INCR_EXPIRE, Arrays.asList(key), (int)duration.getSeconds(), delta);
    }

    public long increment(int delta, LocalDateTime expTime) {
        return increment(delta, Duration.between(LocalDateTime.now(), expTime));
    }

    public long increment(int delta, LocalDate expDate) {
        return increment(delta, Duration.between(LocalDateTime.now(), expDate.atStartOfDay()));
    }

    public long increment(int delta, int value, TimeUnit unit) {
        return increment(delta, Duration.ofSeconds(unit.toSeconds(value)));
    }

    public long increment(int delta, int value) {
        return increment(delta, Duration.ofSeconds(value));
    }

}
